<script setup>
import {User, Lock, Message} from '@element-plus/icons-vue'
import {ref, reactive} from 'vue'
import {ElMessage} from 'element-plus'
import {useTokenStore} from '@/stores/token.js'
import {useRouter, useRoute} from 'vue-router'
import { 
  userRegisterService, 
  userLoginService, 
  sendRegisterCodeService,
  sendLoginCodeService,
  verifyCodeLoginService 
} from '@/api/user.js'

//控制注册与登录表单的显示， 默认显示注册
const isRegister = ref(false)
// 控制登录方式，默认用户名密码登录
const loginType = ref('account') // 'account' | 'code'

//定义数据模型
const registerData = ref({
  username: '',
  password: '',
  rePassword: '',
  email: '',
  verificationCode: '',
  nickname: '' // 添加昵称字段
})

// 登录数据模型
const loginData = ref({
  username: '',
  password: '',
  email: '',
  verificationCode: '',
  role: 'USER'
})

// 倒计时相关
const countdown = ref(0)
const timer = ref(null)

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  if (timer.value) {
    clearInterval(timer.value)
  }
  timer.value = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearInterval(timer.value)
      timer.value = null
    }
  }, 1000)
}

//校验密码的函数
const checkRePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerData.value.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

//定义表单校验规则
const registerRules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 4, max: 20, message: '用户名长度必须在4-20个字符之间', trigger: 'blur'},
    {pattern: /^[a-zA-Z0-9_-]+$/, message: '用户名只能包含字母、数字、下划线和连字符', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 20, message: '密码长度必须在6-20个字符之间', trigger: 'blur'}
  ],
  rePassword: [
    {validator: checkRePassword, trigger: 'blur'}
  ],
  email: [
    {required: true, message: '请输入邮箱', trigger: 'blur'},
    {type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur'}
  ],
  verificationCode: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
    {min: 6, max: 6, message: '验证码长度必须是6位', trigger: 'blur'}
  ],
  nickname: [
    {required: true, message: '请输入昵称', trigger: 'blur'},
    {max: 20, message: '昵称长度不能超过20个字符', trigger: 'blur'}
  ]
}

// 登录表单校验规则
const loginRules = {
  username: [
    {required: loginType.value === 'account', message: '请输入用户名', trigger: 'blur'}
  ],
  password: [
    {required: loginType.value === 'account', message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 20, message: '密码长度必须在6-20个字符之间', trigger: 'blur'}
  ],
  email: [
    {required: loginType.value === 'code', message: '请输入邮箱', trigger: 'blur'},
    {type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur'}
  ],
  verificationCode: [
    {required: loginType.value === 'code', message: '请输入验证码', trigger: 'blur'},
    {min: 6, max: 6, message: '验证码长度必须是6位', trigger: 'blur'}
  ]
}

const registerFormRef = ref(null)
const loginFormRef = ref(null)

// 发送验证码
const sendVerificationCode = async (type = 'login') => {
  try {
    const email = type === 'login' ? loginData.value.email : registerData.value.email
    if (!email) {
      ElMessage.warning('请先输入邮箱地址')
      return
    }

    // 验证邮箱格式
    const emailRule = type === 'login' ? loginRules.email[1] : registerRules.email[1]
    if (!emailRule.pattern.test(email)) {
      ElMessage.warning('请输入正确的邮箱格式')
      return
    }

    const result = type === 'login' 
      ? await sendLoginCodeService(email)
      : await sendRegisterCodeService(email)

    if (result.code === 200) {
      ElMessage.success('验证码已发送到您的邮箱')
      startCountdown()
    } else {
      ElMessage.error(result.message || '验证码发送失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error(error.response?.data?.message || '验证码发送失败')
  }
}

// 注册
const register = async () => {
  if (!registerFormRef.value) return
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 直接进行注册
        const result = await userRegisterService({
          username: registerData.value.username,
          password: registerData.value.password,
          email: registerData.value.email,
          verificationCode: registerData.value.verificationCode,
          nickname: registerData.value.nickname || registerData.value.username // 如果没有设置昵称，使用用户名
        })

        if (result.code === 200) {
          ElMessage.success(result.message || '注册成功')
          isRegister.value = false
          clearRegisterData()
        } else {
          ElMessage.error(result.message || '注册失败')
        }
      } catch (error) {
        console.error('注册失败:', error)
        ElMessage.error(error.response?.data?.message || '注册失败')
      }
    }
  })
}

const router = useRouter()
const route = useRoute()
const tokenStore = useTokenStore()
const role = ref('')

// 登录
const login = async () => {
  if (!loginFormRef.value) return
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let result
        if (loginType.value === 'code') {
          // 验证码登录
          result = await verifyCodeLoginService({
            email: loginData.value.email,
            verificationCode: loginData.value.verificationCode
          })
        } else {
          // 账号密码登录
          result = await userLoginService({
            username: loginData.value.username,
            password: loginData.value.password,
            email: loginData.value.email // 可选字段
          })
        }

        if (result.code === 200) {
          ElMessage.success(result.message || '登录成功')
          
          // 使用 pinia store 存储 token
          tokenStore.setToken(result.data.token)
          
          // 获取重定向地址
          const redirectPath = route.query.redirect || '/'
          
          // 根据角色跳转
          if (result.data.role === 'ADMIN') {
            router.push('/user/admin')
          } else {
            router.push(redirectPath)
          }
        } else {
          ElMessage.error(result.message || '登录失败')
        }
      } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error(error.response?.data?.message || '登录失败')
      }
    }
  })
}

//定义函数,清空数据模型的数据
const clearRegisterData = () => {
  registerData.value = {
    username: '',
    password: '',
    rePassword: '',
    email: '',
    verificationCode: '',
    nickname: ''
  }
  loginData.value = {
    username: '',
    password: '',
    email: '',
    verificationCode: '',
    role: 'USER'
  }
  loginType.value = 'account'
  // 重置表单验证状态
  if (registerFormRef.value) {
    registerFormRef.value.resetFields()
  }
  if (loginFormRef.value) {
    loginFormRef.value.resetFields()
  }
  // 清除倒计时
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
  countdown.value = 0
}

</script>

<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!--       注册表单 -->
      <el-form ref="registerFormRef" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="registerRules">
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input :prefix-icon="Message" placeholder="请输入邮箱" v-model="registerData.email"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="verificationCode">
          <div class="verification-code">
            <el-input 
              placeholder="请输入验证码" 
              v-model="registerData.verificationCode"
            >
              <template #append>
                <el-button 
                  :disabled="countdown > 0" 
                  @click="sendVerificationCode('register')"
                >
                  {{ countdown > 0 ? countdown + '秒后重试' : '获取验证码' }}
                </el-button>
              </template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码"
                    v-model="registerData.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="再次输入密码" prop="rePassword">
          <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码"
                    v-model="registerData.rePassword" show-password></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input :prefix-icon="User" placeholder="请输入昵称" v-model="registerData.nickname"></el-input>
        </el-form-item>
        <!-- 注册按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="register">
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false;clearRegisterData()">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>

      <!-- 登录表单 -->
      <el-form ref="loginFormRef" size="large" autocomplete="off" v-else :model="loginData" :rules="loginRules">
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        
        <!-- 登录方式选择 -->
        <el-form-item>
          <el-radio-group v-model="loginType" size="large">
            <el-radio-button label="account">账号密码登录</el-radio-button>
            <el-radio-button label="code">验证码登录</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <!-- 账号密码登录 -->
        <template v-if="loginType === 'account'">
          <el-form-item prop="username">
            <el-input :prefix-icon="User" placeholder="请输入用户名或邮箱" v-model="loginData.username"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码"
                      v-model="loginData.password" show-password></el-input>
          </el-form-item>
        </template>

        <!-- 验证码登录 -->
        <template v-else>
          <el-form-item prop="email">
            <el-input :prefix-icon="Message" placeholder="请输入邮箱" v-model="loginData.email"></el-input>
          </el-form-item>
          <el-form-item prop="verificationCode">
            <div class="verification-code">
              <el-input placeholder="请输入验证码" v-model="loginData.verificationCode">
                <template #append>
                  <el-button 
                    :disabled="countdown > 0" 
                    @click="sendVerificationCode"
                  >
                    {{ countdown > 0 ? countdown + '秒后重试' : '获取验证码' }}
                  </el-button>
                </template>
              </el-input>
            </div>
          </el-form-item>
        </template>

        <el-form-item prop="role">
          <el-select placeholder="请选择登录身份" size="large" style="width: 100%" v-model="loginData.role">
            <el-option value="ADMIN" label="管理员"></el-option>
            <el-option value="USER" label="普通用户"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
          </div>
        </el-form-item>

        <!-- 登录按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true;clearRegisterData()">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #f5f5f5;
  
  .bg {
    background: url('@/assets/login_bg.jpg') no-repeat center / cover;
    height: 100vh;
  }
  
  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    
    h1 {
      margin: 0 0 20px;
      text-align: center;
    }
    
    .button {
      width: 100%;
    }
    
    .flex {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .verification-code {
    display: flex;
    gap: 10px;
    
    .el-input {
      flex: 1;
    }
  }
}
</style>